import Layout from '@/components/layout/dashboard.vue';
import ParentView from '@/components/layout/parent-view.vue';
import IframeView from '@/components/layout/iframe-view.vue';
import { useAppStore } from '@/stores/app';
import config from '@/config';
import { dynamicRoutes } from './routes';
import { fallbackRoutes } from '@/router/modules/crm-common';
import { useAuthStore } from '@/stores/auth';
// 确保路由、菜单数据
export const ensureRoutesData = async (router: any) => {
  const appStore = useAppStore();
  if (appStore.dynamicRoutesState) return true;
  try {
    const dynamicsRoutes: any = await generateDynamicRoutes();
    const routes: Record<string, any>[] = useDynamicsRoutes(dynamicsRoutes);
    // 访问无权限页面跳转地址
    routes.push(fallbackRoutes[0]);
    console.log('routes', routes);

    // router.options.routes = menus; // ???
    routes.forEach((item: any) => {
      if (!router.hasRoute(item.name)) {
        router.addRoute(item);
      }
    });
    appStore.setDynamicRoutes(routes);
    appStore.setDynamicRoutesState(true);
    return true;
  } catch (e) {
    console.error('console.error', e);
    return false;
  }
};

// 格式化菜单数据
const useDynamicsRoutes = (routes: any[]) => {
  const permissionsMap = useAuthStore().permissionsMap;
  return resolveRoutes(routes);

  // 解析系统菜单
  function resolveRoutes(routesList: any[]) {
    const res: any = [];
    resolveRouteChildren(null, routesList);

    function resolveRouteChildren(parent: any, children?: any[]) {
      if (!children?.length) return;
      // isValidRoute 逻辑用于去掉多级中没有子路由的二级菜单
      children.forEach((o: any) => {
        const { isValidRoute, ...item } = resolveRouteItem(o) || {};
        if (!isValidRoute) return;
        if (parent) {
          if (!parent.children) parent.children = [];
          parent.children.push(item);
          parent.isValidRoute = true;
        } else {
          res.push(item);
        }
      });

    }
    function resolveRouteItem(route: any) {
      const { children, component, ...obj } = route;
      // 用户权限里没有该路由，则不addRoute
      const authCode = obj.meta?.authCode;
      if (authCode && !permissionsMap[authCode] && authCode !== config.adminAuthCode) return null;
      const item = { ...obj };
      if (component) item.component = resolveRouteComponent(component);
      if (component && !children?.length) {
        item.isValidRoute = true;
      }
      resolveRouteChildren(item, children);
      return item;
    }

    return res;
  }

  function resolveRouteComponent(component?: any) {
    if (!component || typeof component !== 'string') return component;
    if (component === 'Layout') {
      return Layout;
    } else if (component === 'ParentView') {// 多级嵌套路由目录
      return ParentView;
    } else if (component === 'IframeView') {// iframe
      return IframeView;
    } else {
      return loadView(component);
    }
  }
};

export const generateDynamicRoutes = () => {
  return dynamicRoutes;
};
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue');
// const regComponentPath = /^\/src\/views\/(.+)\.vue$/g;
const loadView = (view: string) => {
  const res = modules[`/src/views/${view}.vue`] || null;
  return res;
};
